<template>
  <view class="page_root" data-page-name="auth" data-page-identification="b_j9st1n6175">
    <!-- UNI_APP_EXEGESIS_START NAVIGATION_TEMPLATE UNI_APP_EXEGESIS_END -->
  </view>
</template>
<script setup>
  import {
    ref,
    reactive,
    toRaw,
    markRaw,
    watch,
    computed,
    onBeforeMount,
    onMounted,
    onBeforeUnmount,
    onUnmounted,
    onActivated,
    onDeactivated,
    getCurrentInstance,
  } from 'vue';
  import { useRoute } from 'vue-router';
  const route = useRoute();
  import { get, post, put, del, request, requestWithHeaders } from '@/utils/http/Axios';
  import {
    cloneDeep,
    localGet,
    traversalTreeStructure,
    set,
    checkCaseCondition,
    throttle,
    merge,
    debounce,
    getGridStyle,
    getCellRenderAble,
    formulaStrategy,
    getApplicationId,
    getComponentParamsValue,
    get as lodashGet,
  } from '@/utils/index';
  import {
    isEqual,
    isNullOrEmpty,
    isEmptyArr,
    isArray,
    isEmpty,
    isNullOrUnDef,
    isContained,
  } from '@/utils/is';
  import { CovertOptions, getChartsDataSourceConvert } from '@/utils/chart';
  import {
    propertyFormatByNumber,
    propertyFormatByPercentage,
    propertyFormatByDate,
    parseSubFromDataList,
  } from '@/utils/format';
  import { checkCommonCondition, getResultByCurrentCommonCondition } from '@/utils/formCondition';
  import { FormFormat } from '@/utils/formFormat';
  import { customAddWaterMarkFunc, generateWaterMarkText } from '@/utils/addWaterMark';
  import dayjs from 'dayjs';
  import hashSum from 'hash-sum';
  /*** UNI_APP_EXEGESIS ***
  import { handleRedirect, permission, parseJson } from '@/utils/common';
  import { onPullDownRefresh, onLoad, onReady, onShow, onHide, onPageScroll, onUnload } from '@dcloudio/uni-app';
  import { BroadcastMessage } from '@/utils/BroadcastMessage';
  import { sendToken } from "@/hooks/useIframeToken";
  *** UNI_APP_EXEGESIS ***/

  // ---------------------------- 属性定义 ----------------------------
  const sourceId = 'page50001883';

  // 获取传入的流程ID和组件参数
  const props = defineProps({
    processInstanceId: {
      type: [String, Number, Boolean],
      default: undefined,
    },
    hideNav: {
      type: [Boolean],
      default: undefined,
    },
  });

  // 组件参数默认值
  const componentParamsDefaultProps = {};

  // 是否显示菜单按钮
  const isMenuIconShow = false;
  // NAVIGATION_MENU
  const handleShowNavigation = () => {};

  let isProcessState = ref(false);

  const setTimeOutList = [];

  // ============================ 属性定义 ============================

  // ---------------------------- 元素数据引用 ----------------------------
  // 动态key的map
  const fieldTypeMap = {};
  // 动态key的map
  const refMap = {};

  const showState = reactive({});
  // ============================ 元素数据引用 ============================

  // ---------------------------- 数据 ----------------------------

  // ============================ 数据 ============================

  // ---------------------------- 方法 ----------------------------
  // ---------------------------- 页面数据 ----------------------------

  // ============================ 页面数据 ============================

  // ---------------------------- 数据字典 ----------------------------

  // ============================ 数据字典 ============================

  // ---------------------------- 响应 ----------------------------

  // ============================ 响应 ============================

  // ---------------------------- 函数 ----------------------------

  // 自定义函数 返回上一页
  const customFunction_goBack_k4z93223fy = (params) => {
    uni.navigateBack();
  };

  // ============================ 函数 ============================

  // ---------------------------- 页面参数 ----------------------------

  const pageParameter_state = reactive({
    processInstanceId: undefined,
  });

  // ============================ 页面参数 ============================

  // ---------------------------- 组件事件处理方法 ----------------------------

  // ============================ 组件事件处理方法 ============================

  // ============================ 方法 ============================

  // ---------------------------- 生命周期 ----------------------------
  /*** UNI_APP_EXEGESIS ***
      // 获取上一层传递的数据
      const workflowChannel = new BroadcastMessage('WORKFLOW');
      workflowChannel.publish({ status: 'Ready' });
      workflowChannel.subscribe((data) => {
        if (data) {
          isProcessState.value = (window.self !== window.parent && data.type === 'hideHeader');
        }
      });
      *** UNI_APP_EXEGESIS ***/

  const pageScrollTop = ref(0);

  // *** PREVIEW_EXEGESIS ***
  onMounted(() => {
    setPageParams(route.query);
    // 设置表单的rule
    try {
    } catch {
      // do nothing
    }
  });
  // *** PREVIEW_EXEGESIS *** //

  /*** UNI_APP_EXEGESIS ***
  const routeOption = ref({})
  onLoad((option) => {
    routeOption.value = option;
  });
  onReady(() => {
    setPageParams(routeOption.value)
    // 设置表单的rule
    try{

    }catch{
        // do nothing
    }
  });
  // 图表刷新标记
  const uChartsReshowFlag = ref(false);
  onHide(() => { // 页面隐藏后标记置为false(如果不置为false无法触发图表更新)
      uChartsReshowFlag.value = false
  })
  onShow(() => {
      uChartsReshowFlag.value = true; // 页面激活后,标记置为true

      setPageParams(routeOption.value)
  })
  onPageScroll(e => {
      pageScrollTop.value = e.scrollTop
  });
  *** UNI_APP_EXEGESIS ***/

  let setPageParams = (routerParam) => {
    const pageParams = [{ dataType: 'STRING', name: 'processInstanceId' }];
    const strategyMap = {
      STRING: (param, paramValue) => {
        pageParameter_state[param.name] = paramValue;
      },
      BOOLEAN: (param, paramValue) => {
        if ('true' === (paramValue || '').toLowerCase()) {
          pageParameter_state[param.name] = true;
        } else if ('false' === (paramValue || '').toLowerCase()) {
          pageParameter_state[param.name] = false;
        } else {
          // TODO: 是否要支持toast
          console.error('参数传入错误！类型不匹配！');
        }
      },
      NUMBER: (param, paramValue) => {
        if (!isNaN(paramValue)) {
          pageParameter_state[param.name] = Number(paramValue);
        } else {
          // TODO: 是否要支持toast
          console.error('参数传入错误！类型不匹配！');
        }
      },
      ARRAY: (param, paramValue) => {
        if (isNullOrUnDef(paramValue) || !paramValue || paramValue === 'undefined') {
          // default value
          pageParameter_state[param.name] = [];
        } else if (paramValue.trim().startsWith('[') && paramValue.trim().endsWith(']')) {
          try {
            pageParameter_state[param.name] = JSON.parse(decodeURI(paramValue));
          } catch (error) {
            console.error('参数解析失败 ', error);
          }
        } else {
          console.error('参数传入错误！类型不匹配！');
        }
      },
    };
    pageParams.forEach((param) => {
      strategyMap[param.dataType](param, routerParam[param.name]);
    });
  };

  onUnmounted(() => {
    // 销毁定时器
    setTimeOutList.forEach(({ repeat, timer }) => {
      repeat ? clearInterval(timer) : clearTimeout(timer);
    });
  });

  /*** UNI_APP_EXEGESIS ***
  onPullDownRefresh(() => {
    // 下拉刷新
    setTimeout(() => {
        uni.stopPullDownRefresh()
    }, 1000)
  })
  *** UNI_APP_EXEGESIS ***/

  // ============================ 生命周期 ============================

  // ---------------------------- 数据关联处理 ----------------------------
  // ---------------------------- 组件数据同步 ----------------------------

  // ============================ 组件数据同步 ============================
  //
  // ============================ 数据关联处理 ============================

  // ---------------------- 不同组件自定义的处理逻辑 ---------------------

  // ====================== 不同组件自定义的处理逻辑 ======================

  // ================================定制化逻辑========================================
  const stateForm = reactive({
    tenantId: null,
    sessionKey: null,
    userId: null,
    mobile: null,
    productId: null,
    getTidUrl: null,
    newUrl: null,
  });

  const debuggerState = reactive({
    first: {
      status: '',
      content: '',
    },
    two: {
      status: '',
      content: '',
    },
    three: {
      status: '',
      content: '',
    },
    four: {
      status: '',
      content: '',
    },
    five: {
      status: '',
      content: '',
    },
  });
  var currentURL = window.location.href;

  // 获取当前页面url的传参
  function getParameterByName(name, url = window.location.href) {
    name = name.replace(/[\[\]]/g, '\\$&');
    var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
      results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, ' '));
  }

  stateForm.sessionKey = getParameterByName('sessionKey', currentURL);
  stateForm.userId = getParameterByName('userId', currentURL);
  stateForm.mobile = getParameterByName('mobile', currentURL);
  // 获取当前页面url的传参
  async function getTenantId() {
    try {
      debuggerState.two.status = '第二步获取tenantId开始';
      let firstSlashIndex = stateForm.newUrl.indexOf('/', 8);
      let prefix;

      if (firstSlashIndex !== -1) {
        prefix = stateForm.newUrl.substring(0, firstSlashIndex);
        let protocols = ['http://', 'https://'];
        let protocol = protocols.find((p) => prefix.includes(p));

        if (protocol) {
          let result = prefix.substring(protocol.length);
          // result = result + '/app_50000005/';
          console.log(result, 'result');
          let data = await post(`/base/api/v1/product/url`, {
            url: result,
            // url: 'ppm-stage.allintechinc.com'
          });
          if (data.status === 'success') {
            // 获取到的tenantId
            stateForm.tenantId = data.data.tenantId;
            stateForm.productId = data.data.id;
            // 成功获取之后登陆操作
            getUser();
            debuggerState.two.content = `第二步成功-----tenantId是${data.data.tenantId},productId是${data.data.id}`;
          } else {
            console.error('获取tenantId失败');
            debuggerState.two.content = `获取tenantId失败${data.errorMsg},传值是${result}`;
          }
        } else {
          console.error('未找到 `http://` 或 `https://`');
        }
      } else {
        console.error('无法提取前缀');
      }
    } catch (error) {
      console.error('getTenantId出现错误:', error);
    }
  }

  function getUser() {
    try {
      debuggerState.three.status = '第三步判断登录状态开始';
      // let localStorageData = localStorage.getItem('app-user-store');
      let localStorageDataDP = localStorage.getItem('app-user');
      // debugger
      if (localStorageDataDP !== null) {
        localStorageDataDP = JSON.parse(localStorageDataDP);
        if (localStorageDataDP.token !== null) {
          debuggerState.three.status =
            '第三步判断登录状态开始-有token调接口校验token的可行性。。。';
          console.log('有token调接口校验token的可行性');
          checkToken(localStorageDataDP.token, localStorageDataDP.uuid);
        } else {
          debuggerState.three.status = '第三步判断登录状态开始-没有token，去登录。。。';
          getToken();
        }
      } else {
        getToken();
      }
    } catch (error) {
      console.error('getUser出现错误:', error);
    }
  }
  async function checkToken(token, uuid) {
    try {
      debuggerState.four.status = '第四步校验token';
      let params = {
        uuid: uuid,
        token: token,
        appId: 'app_preview',
      };
      let result = await post('/base/api/v1/valid', params);
      if (result.data === null) {
        // 如果data为null，则执行getToken操作
        debuggerState.four.status = '第四步校验token---校验失败去重新登录';
        getToken();
      } else {
        debuggerState.four.status = '第四步校验token---校验成功去跳转页面';
        // 如果data不为null，则执行getNewUrl操作
        let newUserData = {
          uuid: uuid,
          token: token,
          productId: stateForm.productId,
          tenantId: stateForm.tenantId,
          appid: 'app_preview',
        };
        localStorage.setItem('app-user', JSON.stringify(newUserData));
        localStorage.setItem('app-user-store', JSON.stringify(newUserData));
        debuggerState.four.content = `存储结果${JSON.stringify(newUserData)}`;
        console.log('执行');
        console.log(localStorage.getItem('app-user-store'));
        // window.location.href = stateForm.getTidUrl
        handleRedirect(`/pages/Page3000001233/Page3000001233`);
      }
    } catch (error) {
      getToken();
      console.error('checkToken出现错误:', error);
    }
  }
  async function getToken() {
    try {
      debuggerState.five.status = '第五步登录获取信息';
      let uuid = '';
      let token = '';
      const params = {
        sessionKey: stateForm.sessionKey,
        mobile: stateForm.mobile,
        appId: 'app_preview',
        withTenantIdFlag: false,
        mobileIsUserName: false,
        tenantId: stateForm.tenantId,
      };
      let result = await post('/base/api/v1/open/login', params);
      console.log(result.status, 'getTokenstatus');
      if (result.data) {
        console.log(result, '登陆接口返回');
        debuggerState.five.content = `第五步登录获取信息--登陆接口返回${result}`;
        uuid = result.data.uuid;
        token = result.data.token;
        let newUserData = {
          uuid: uuid,
          token: token,
          productId: stateForm.productId,
          tenantId: stateForm.tenantId,
          appid: 'app_preview',
        };
        localStorage.setItem('app-user-store', JSON.stringify(newUserData));
        localStorage.setItem('app-user', JSON.stringify(newUserData));
        console.log('执行');
        console.log(localStorage.getItem('app-user-store'));
        // window.location.href = stateForm.getTidUrl;
        handleRedirect(`/pages/Page3000001233/Page3000001233`);
        debuggerState.five.status = '第五步登录获取信息--跳转成功';
      } else {
        uni.showToast({
          title: '非法账号',
          icon: 'error',
        });
        debuggerState.five.content = `第五步登录获取信息--失败${result.errorMsg}`;
      }
    } catch (error) {
      console.error('getToken出现错误:', error);
      uni.showToast({
        title: '非法账号',
        icon: 'error',
      });
      debuggerState.five.content = `第五步登录获取信息--失败${error}`;
    }
  }

  // 第一步获取当前用户跳转的地址
  async function getNewUrl() {
    try {
      debuggerState.first.status = '获取跳转url步骤开始';
      const response = await post(
        '/solution-ppm/api/v2/built-in-system-ppm/wechat_auth_config/query/user_address',
        {
          userId: stateForm.userId,
        },
      );
      const result = response.data; // 获取响应数据
      console.log(result, '跳转地址');
      if (result.productUri) {
        // 这是最后一步跳转该用户应该跳转的页面
        stateForm.getTidUrl = result.appUri;
        // 这是第二步获取tenantId传给base的链接获取对应的tenantId
        stateForm.newUrl = result.productUri;
        // 进行第二步获取当前产品的tenantId
        getTenantId();
        debuggerState.first.content = `用户最后跳转的页面地址${result.appUri}第二步获取tenantId传给base的链接${result.productUri}`;
      }
    } catch (error) {
      // 请求失败时调用 getToken
      getToken();

      // 这里处理请求错误
      console.log('getNewUrl出现错误:', error);
    }
  }
  // 清除 app-user-store 的数据
  onMounted(() => {
    localStorage.removeItem('app-user-store');
    console.log('清除');
    console.log(localStorage.getItem('app-user-store'));
  });
  // 清除 app-user-store 的数据
  getNewUrl();
</script>
<style lang="less" scoped>
  .page_root {
    min-height: 100%;
    box-sizing: border-box;
    overflow: auto;
  }
</style>
